import sys
import os, os.path
import glob
from PyQt4 import QtCore
from PluginBase import Plugin


_instances = {}

    
def get_plugin_by_keyword(keyword):
    if len(_instances) == 0:
        for plugin in Plugin.__subclasses__():
            p = plugin()
            _instances[p.get_keyword()] = p
    if _instances.has_key(keyword):
        return _instances[keyword]
    else:
        return None


def get_all_plugins():
    if len(_instances) == 0:
        for plugin in Plugin.__subclasses__():
            p = plugin()
            _instances[p.get_keyword()] = p
    return _instances.values()


def load_plugins(pluginpath):
    plugins = glob.glob(os.path.join(pluginpath, "*.py"))
    for plugin in plugins:
        name = os.path.split(plugin)[1]
        __import__(name[: - 3], None, None, [''])


def init_plugin_system():
    settings = QtCore.QSettings()
    pluginpath = str(settings.value("plugins_path", QtCore.QVariant(QtCore.QString("./plugins"))).toString())
    if not pluginpath in sys.path:
        sys.path.insert(0, pluginpath)
    load_plugins(pluginpath)
    

def find_plugins():
    return Plugin.__subclasses__()